import os
from glob import glob

env = Environment()

platform = str(Platform())

libData = {'libs':[],'incDirs':[],'libDirs':[],'copyFiles':[]}

if env.GetOption('clean'):
    if ARGUMENTS.get('cleanLibs',False):
        ogreClean = 'make clean; rm -f ogreBuilt'
        freeImageClean = 'make -C FreeImage clean; rm -f freeImageBuilt'
    
        os.system(ogreClean)
        os.system(freeImageClean)

elif 'win' in platform:
    print "how do I built windows? \\(O.o)/"

else:
    ogreFilename = 'ogre-linux_osx-v1-4-5.tar.bz2'
    ogreDownload = 'http://internap.dl.sourceforge.net/sourceforge/ogre/%s' % ogreFilename

    if not os.path.isfile(ogreFilename):
        os.system('wget %s' % ogreDownload)
        
    if not os.path.isdir('ogrenew'):
        os.system('tar xjf %s' % ogreFilename)
        os.system('mv ogrenew/* .')
        
    freeImageFile = 'FreeImage393.zip'
    freeImageDownload = 'http://superb-west.dl.sourceforge.net/sourceforge/freeimage/%s' % freeImageFile
    
    if not os.path.isfile(freeImageFile):
        os.system('wget %s' % freeImageDownload)
        
    if not os.path.isdir('FreeImage'):
        os.system('unzip FreeImage393.zip')
        
    cgFile = 'Cg-1.5_Sep2007_x86.tar.gz'
    cgDownload = 'http://developer.download.nvidia.com/cg/Cg_1.5/1.5.0023/%s' % cgFile
    
    if not os.path.isfile(cgFile):
        os.system('wget %s' % cgDownload)
        
    if not os.path.isdir('cg'):
        os.system('tar xif Cg-1.5_Sep2007_x86.tar.gz && mv usr cg')

    freeImageBuild = 'make -C FreeImage && touch freeImageBuilt'
    if not os.path.isfile('freeImageBuilt'):
        os.system(freeImageBuild)
    
    freeImageDist = os.path.abspath('FreeImage/Dist')
    libData['libDirs'].append(freeImageDist)
    libData['incDirs'].append(freeImageDist)
    libData['libs'].append('freeimage')
    
    cgLibDir = os.path.abspath('cg/lib')
    cgIncDir = os.path.abspath('cg/include')
    libData['libDirs'].append(cgLibDir)
    libData['incDirs'].append(cgIncDir)
    libData['libs'] += ['CgGL','Cg','GL','pthread']
    
    ogreLibDir = os.path.abspath('libs/lib')
    ogreIncDir = os.path.abspath('libs/include/OGRE')
    libData['libDirs'].append(ogreLibDir)
    libData['incDirs'].append(ogreIncDir)
    libData['libs'].append('OgreMain')
    
    
    prefix = 'LDFLAGS=\"-L%s -L%s\" CPPFLAGS=\"-I%s -I%s\"' % (freeImageDist,cgLibDir,freeImageDist,cgIncDir)
    ogreConfig = '%s ./configure --prefix $(pwd)/libs' % prefix
    ogreBuild = '%s make && make install && touch ogreBuilt' % prefix
    if not os.path.isfile('Makefile'):
        os.system(ogreConfig)
    if not os.path.isfile('ogreBuilt'):
        os.system(ogreBuild)
    
if 'win' not in platform:
    ogreFiles = [os.path.abspath(file) for file in glob('Samples/Common/bin/*.cfg')]
    libData['copyFiles'].extend(filter(lambda x: 'resources.cfg' not in x, ogreFiles))
    
Return('libData')
